package com.tbynet.jwp.repository.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.tbynet.jwp.framework.aop.Aop;
import com.tbynet.jwp.framework.core._JwpServiceProvider;
import com.tbynet.jwp.framework.kit.SlugKit;
import com.tbynet.jwp.framework.kit.StringKit;
import com.tbynet.jwp.model.Postmeta;
import com.tbynet.jwp.model.Posts;
import com.tbynet.jwp.repository.spi.PostService;

/**
 * 文章服务实现类
 * Service层职责：单一的数据操作，包含SQL代码，不处理事务
 *
 * @author 佰亿互联
 * @version 2.0
 * @since 2025-11-04
 */
@Aop(PostService.class)
public class PostServiceImpl extends _JwpServiceProvider<Posts> implements PostService {

    /** 文章元数据DAO对象 */
    private Postmeta postmetaDao = new Postmeta().dao();

    @Override
    protected String buildSearchWhereSql(String keyword, List<Object> params) {
        if (StrKit.notBlank(keyword)) {
            params.add("%" + keyword + "%");
            params.add("%" + keyword + "%");
            return " WHERE (post_title LIKE ? OR post_content LIKE ?)";
        }
        return " WHERE 1=1";
    }

    /**
     * 根据ID和类型获取文章
     * Service层职责：单一的数据查询操作
     *
     * @param ID 文章ID
     * @param type 文章类型
     * @return 文章对象
     */
    @Override
    public Posts getPost(Object ID, String type) {
        return executeWithResultLogging("getPost", () -> {
            validateNotNull(ID, "文章ID不能为空");
            validateNotBlank(type, "文章类型不能为空");

            log.debug("根据ID和类型获取文章，ID: %s, 类型: %s", ID, type);
            return getDao().findFirst("select * from wp_posts where ID=? and post_type=? limit 1", ID, type);
        }, ID, type);
    }

    @Override
    public Posts getPostWithAnyStatus(Object ID) {
        return executeWithResultLogging("getPostWithAnyStatus", () -> {
            validateNotNull(ID, "文章ID不能为空");

            log.debug("根据ID获取文章（包含所有状态），ID: %s", ID);
            return getDao().findById(ID);
        }, ID);
    }

    @Override
    public Posts getPostBySlug(String slug, String type, String status) {
        return executeWithResultLogging("getPostBySlug", () -> {
            validateNotBlank(slug, "文章别名不能为空");

            log.debug("根据别名获取文章，别名: %s, 类型: %s, 状态: %s", slug, type, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("select * from wp_posts where post_name=?");
            params.add(slug);

            if (StrKit.notBlank(type)) {
                sql.append(" and post_type=?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" and post_status=?");
                params.add(status);
            }

            sql.append(" limit 1");
            return getDao().findFirst(sql.toString(), params.toArray());
        }, slug, type, status);
    }

    @Override
    public boolean createPost(Posts post, List<Postmeta> postmetas) {
        return executeWithBooleanLogging("createPost", () -> {
            validateNotNull(post, "文章对象不能为空");

            log.debug("创建新文章，标题: %s", post.getPostTitle());

            // 保存文章
            if (!post.save()) {
                log.error("保存文章失败");
                return false;
            }

            // 保存元数据
            if (postmetas != null && !postmetas.isEmpty()) {
                return savePostMetas(post.getID(), postmetas);
            }

            return true;
        }, post.getPostTitle());
    }

    @Override
    public boolean updatePost(Posts post, List<Postmeta> postmetas) {
        return executeWithBooleanLogging("updatePost", () -> {
            validateNotNull(post, "文章对象不能为空");
            validateEntityHasPrimaryKey(post);

            log.debug("更新文章，ID: %s, 标题: %s", post.getID(), post.getPostTitle());

            // 更新文章
            if (!post.update()) {
                log.error("更新文章失败");
                return false;
            }

            // 更新元数据
            if (postmetas != null) {
                return updatePostMetas(post.getID(), postmetas);
            }

            return true;
        }, post.getID(), post.getPostTitle());
    }

    @Override
    public boolean trashPost(Object postId) {
        return executeWithBooleanLogging("trashPost", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("移动文章到回收站，ID: %s", postId);

            int result = Db.update("UPDATE wp_posts SET post_status = ? WHERE ID = ?",
                    Posts.POST_STATUS_TRASH, postId);
            return result > 0;
        }, postId);
    }

    @Override
    public boolean deletePostPermanently(Object postId) {
        return executeWithBooleanLogging("deletePostPermanently", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("永久删除文章，ID: %s", postId);

            // 先删除元数据
            deletePostMetas(postId);

            // 再删除文章
            int result = Db.update("DELETE FROM wp_posts WHERE ID = ?", postId);
            return result > 0;
        }, postId);
    }

    @Override
    public boolean restorePost(Object postId) {
        return executeWithBooleanLogging("restorePost", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("从回收站恢复文章，ID: %s", postId);

            int result = Db.update("UPDATE wp_posts SET post_status = ? WHERE ID = ?",
                    Posts.POST_STATUS_PUBLISH, postId);
            return result > 0;
        }, postId);
    }

    @Override
    public boolean exists(Object postId) {
        return executeWithBooleanLogging("exists", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("检查文章是否存在，ID: %s", postId);
            return getPostWithAnyStatus(postId) != null;
        }, postId);
    }

    /**
     * 统计文章数量
     * Service层职责：单一的数据统计操作
     *
     * @param status 文章状态
     * @return 文章数量
     */
    @Override
    public int count(String status) {
        return executeWithResultLogging("count", () -> {
            log.debug("统计文章数量，状态: %s", status);

            List<Object> paras = new ArrayList<Object>();
            StringBuilder sql = new StringBuilder("select count(*) from wp_posts where 1=1 ");

            if(StrKit.notBlank(status)) {
                sql.append(" AND post_status=? ");
                paras.add(status);
            } else {
                sql.append(" AND post_status!=? ");
                paras.add(Posts.POST_STATUS_TRASH);
            }

            return Db.queryInt(sql.toString(), paras.toArray());
        }, status).intValue();
    }

    @Override
    public int count(String type, String status) {
        return executeWithResultLogging("count", () -> {
            log.debug("统计文章数量，类型: %s, 状态: %s", type, status);

            List<Object> paras = new ArrayList<Object>();
            StringBuilder sql = new StringBuilder("select count(*) from wp_posts where 1=1 ");

            if(StrKit.notBlank(type)) {
                sql.append(" AND post_type=? ");
                paras.add(type);
            }

            if(StrKit.notBlank(status)) {
                sql.append(" AND post_status=? ");
                paras.add(status);
            } else {
                sql.append(" AND post_status!=? ");
                paras.add(Posts.POST_STATUS_TRASH);
            }

            return Db.queryInt(sql.toString(), paras.toArray());
        }, type, status).intValue();
    }

    @Override
    public int countAll() {
        return executeWithResultLogging("countAll", () -> {
            log.debug("统计所有文章数量");
            return Db.queryInt("SELECT COUNT(*) FROM wp_posts WHERE post_status != ?", Posts.POST_STATUS_TRASH);
        }).intValue();
    }

    @Override
    public int countByUser(Object userId, String type, String status) {
        return executeWithResultLogging("countByUser", () -> {
            validateNotNull(userId, "用户ID不能为空");

            log.debug("统计用户文章数量，用户ID: %s, 类型: %s, 状态: %s", userId, type, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM wp_posts WHERE post_author = ?");
            params.add(userId);

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status != ?");
                params.add(Posts.POST_STATUS_TRASH);
            }

            return Db.queryInt(sql.toString(), params.toArray());
        }, userId, type, status).intValue();
    }

    /**
     * 获取文章所有元数据
     * Service层职责：单一的元数据查询操作
     *
     * @param ID 文章ID
     * @return 元数据列表
     */
    @Override
    public List<Postmeta> getPostmetas(Object ID) {
        return executeWithResultLogging("getPostmetas", () -> {
            validateNotNull(ID, "文章ID不能为空");

            log.debug("获取文章所有元数据，文章ID: %s", ID);
            return postmetaDao.find("select * from wp_postmeta where post_id=?", ID);
        }, ID);
    }

    /**
     * 获取文章指定元数据
     * Service层职责：单一的元数据查询操作
     *
     * @param ID 文章ID
     * @param metaKeys 元数据键数组
     * @return 元数据列表
     */
    @Override
    public List<Postmeta> getPostmetas(Object ID, String... metaKeys) {
        return executeWithResultLogging("getPostmetas", () -> {
            validateNotNull(ID, "文章ID不能为空");
            validateNotNull(metaKeys, "元数据键不能为空");

            log.debug("获取文章指定元数据，文章ID: %s, 元数据键: %s", ID, metaKeys);

            List<Object> paras = new ArrayList<Object>();
            StringBuilder sql = new StringBuilder("select * from wp_postmeta where post_id=?");
            paras.add(ID);

            for(String metaKey : metaKeys) {
                sql.append(" and meta_key=? ");
                paras.add(metaKey);
            }

            return postmetaDao.find(sql.toString(), paras.toArray());
        }, ID, (Object) metaKeys);
    }

    /**
     * 获取文章单个元数据
     * Service层职责：单一的元数据查询操作
     *
     * @param ID 文章ID
     * @param metaKey 元数据键
     * @return 元数据对象
     */
    @Override
    public Postmeta getPostmeta(Object ID, String metaKey) {
        return executeWithResultLogging("getPostmeta", () -> {
            validateNotNull(ID, "文章ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            log.debug("获取文章单个元数据，文章ID: %s, 元数据键: %s", ID, metaKey);
            return postmetaDao.findFirst("select * from wp_postmeta where post_id=? and meta_key=? limit 1", ID, metaKey);
        }, ID, metaKey);
    }

    @Override
    public String getPostmetaValue(Object ID, String metaKey) {
        return executeWithResultLogging("getPostmetaValue", () -> {
            validateNotNull(ID, "文章ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            log.debug("获取文章元数据值，文章ID: %s, 元数据键: %s", ID, metaKey);
            Postmeta meta = getPostmeta(ID, metaKey);
            return meta != null ? meta.getMetaValue() : "";
        }, ID, metaKey);
    }

    @Override
    public String getPostmetaValue(Object ID, String metaKey, String defaultValue) {
        return executeWithResultLogging("getPostmetaValue", () -> {
            validateNotNull(ID, "文章ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            log.debug("获取文章元数据值（带默认值），文章ID: %s, 元数据键: %s", ID, metaKey);
            Postmeta meta = getPostmeta(ID, metaKey);
            return meta != null ? meta.getMetaValue() : defaultValue;
        }, ID, metaKey, defaultValue);
    }

    /**
     * 保存文章元数据
     * Service层职责：单一的元数据保存操作
     *
     * @param postId 文章ID
     * @param postmetas 元数据列表
     * @return 保存结果
     */
    @Override
    public boolean savePostMetas(Object postId, List<Postmeta> postmetas) {
        return executeWithBooleanLogging("savePostMetas", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("保存文章元数据，文章ID: %s, 元数据数量: %s", postId,
                    postmetas != null ? postmetas.size() : 0);

            if (postmetas == null || postmetas.isEmpty()) {
                return true;
            }

            for (Postmeta meta : postmetas) {
                meta.setPostId(new BigInteger(postId.toString()));
                if (!meta.save()) {
                    log.error("保存文章元数据失败，文章ID: %s, 元数据键: %s", postId, meta.getMetaKey());
                    return false;
                }
            }
            return true;
        }, postId, postmetas != null ? postmetas.size() : 0);
    }

    /**
     * 更新文章元数据
     * Service层职责：单一的元数据更新操作
     *
     * @param postId 文章ID
     * @param postmetas 元数据列表
     * @return 更新结果
     */
    @Override
    public boolean updatePostMetas(Object postId, List<Postmeta> postmetas) {
        return executeWithBooleanLogging("updatePostMetas", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("更新文章元数据，文章ID: %s, 元数据数量: %s", postId,
                    postmetas != null ? postmetas.size() : 0);

            // 先删除旧的元数据
            boolean deleteSuccess = deletePostMetas(postId);
            if (!deleteSuccess) {
                log.error("删除旧元数据失败，文章ID: %s", postId);
                return false;
            }

            // 保存新的元数据
            return savePostMetas(postId, postmetas);
        }, postId, postmetas != null ? postmetas.size() : 0);
    }

    @Override
    public boolean addOrUpdatePostmeta(Object postId, String metaKey, String metaValue) {
        return executeWithBooleanLogging("addOrUpdatePostmeta", () -> {
            validateNotNull(postId, "文章ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            log.debug("添加或更新文章元数据，文章ID: %s, 元数据键: %s", postId, metaKey);

            // 先尝试查找是否已存在
            Postmeta existingMeta = getPostmeta(postId, metaKey);

            if (existingMeta != null) {
                // 更新现有元数据
                existingMeta.setMetaValue(metaValue);
                return existingMeta.update();
            } else {
                // 创建新元数据
                Postmeta newMeta = new Postmeta();
                newMeta.setPostId(new BigInteger(postId.toString()));
                newMeta.setMetaKey(metaKey);
                newMeta.setMetaValue(metaValue);
                return newMeta.save();
            }
        }, postId, metaKey);
    }

    /**
     * 根据ID列表获取文章
     * Service层职责：单一的批量数据查询操作
     *
     * @param postIds 文章ID列表
     * @return 文章列表
     */
    @Override
    public List<Posts> getPostsByIds(List<Integer> postIds) {
        return executeWithResultLogging("getPostsByIds", () -> {
            log.debug("根据ID列表获取文章，文章数量: %s", postIds != null ? postIds.size() : 0);

            if (postIds == null || postIds.isEmpty()) {
                return new ArrayList<>();
            }

            // 构建IN查询
            String inClause = buildInClause(postIds);
            List<Object> paras = new ArrayList<>(postIds);

            String sql = "SELECT * FROM wp_posts WHERE ID IN (" + inClause + ") AND post_status = ? ORDER BY post_date DESC";
            paras.add(Posts.POST_STATUS_PUBLISH);

            return getDao().find(sql, paras.toArray());
        }, postIds != null ? postIds.size() : 0);
    }

    /**
     * 根据标题查找文章
     * Service层职责：单一的条件查询操作
     *
     * @param title 文章标题
     * @return 文章对象
     */
    @Override
    public Posts findPostByTitle(String title) {
        return executeWithResultLogging("findPostByTitle", () -> {
            validateNotBlank(title, "文章标题不能为空");

            log.debug("根据标题查找文章，标题: %s", title);
            return getDao().findFirst("SELECT * FROM wp_posts WHERE post_title = ? AND post_type = 'post' LIMIT 1", title);
        }, title);
    }

    @Override
    public List<Posts> searchPosts(String keyword, String type, String status, int limit) {
        return executeWithResultLogging("searchPosts", () -> {
            log.debug("搜索文章，关键词: %s, 类型: %s, 状态: %s, 限制: %s", keyword, type, status, limit);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT * FROM wp_posts WHERE 1=1");

            if (StrKit.notBlank(keyword)) {
                sql.append(" AND (post_title LIKE ? OR post_content LIKE ?)");
                params.add("%" + keyword + "%");
                params.add("%" + keyword + "%");
            }

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status != ?");
                params.add(Posts.POST_STATUS_TRASH);
            }

            sql.append(" ORDER BY post_date DESC");

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return getDao().find(sql.toString(), params.toArray());
        }, keyword, type, status, limit);
    }

    @Override
    public List<String> getAllPostTypes() {
        return executeWithResultLogging("getAllPostTypes", () -> {
            log.debug("获取所有文章类型");
            List<Record> records = Db.find("SELECT DISTINCT post_type FROM wp_posts");
            List<String> types = new ArrayList<>();
            for (Record record : records) {
                types.add(record.getStr("post_type"));
            }
            return types;
        });
    }

    @Override
    public List<Posts> getStickyPosts(int limit, String type, String status) {
        return executeWithResultLogging("getStickyPosts", () -> {
            log.debug("获取置顶文章，限制: %s, 类型: %s, 状态: %s", limit, type, status);

            List<Integer> stickyPostIds = getStickyPostIds();
            if (stickyPostIds.isEmpty()) {
                return new ArrayList<>();
            }

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT * FROM wp_posts WHERE ID IN (");
            sql.append(buildInClause(stickyPostIds));
            params.addAll(stickyPostIds);
            sql.append(")");

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            }

            sql.append(" ORDER BY post_date DESC");

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return getDao().find(sql.toString(), params.toArray());
        }, limit, type, status);
    }

    @Override
    public List<Posts> getRandomPosts(int limit, String type, String status) {
        return executeWithResultLogging("getRandomPosts", () -> {
            log.debug("获取随机文章，限制: %s, 类型: %s, 状态: %s", limit, type, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT * FROM wp_posts WHERE 1=1");

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status != ?");
                params.add(Posts.POST_STATUS_TRASH);
            }

            sql.append(" ORDER BY RAND()");

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return getDao().find(sql.toString(), params.toArray());
        }, limit, type, status);
    }

    /**
     * 删除文章元数据
     * Service层职责：单一的元数据删除操作
     *
     * @param postId 文章ID
     * @return 删除结果
     */
    @Override
    public boolean deletePostMetas(Object postId) {
        return executeWithBooleanLogging("deletePostMetas", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("删除文章元数据，文章ID: %s", postId);

            int result = Db.delete("DELETE FROM wp_postmeta WHERE post_id=?", postId);
            log.debug("删除文章元数据完成，影响行数: %s", result);
            return result >= 0; // 删除0条也算成功（可能本来就没有元数据）
        }, postId);
    }

    @Override
    public boolean deletePostmeta(Object postId, String metaKey) {
        return executeWithBooleanLogging("deletePostmeta", () -> {
            validateNotNull(postId, "文章ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            log.debug("删除指定文章元数据，文章ID: %s, 元数据键: %s", postId, metaKey);

            int result = Db.delete("DELETE FROM wp_postmeta WHERE post_id = ? AND meta_key = ?", postId, metaKey);
            return result > 0;
        }, postId, metaKey);
    }

    @Override
    public boolean postmetaExists(Object postId, String metaKey) {
        return executeWithBooleanLogging("postmetaExists", () -> {
            validateNotNull(postId, "文章ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            log.debug("检查文章元数据是否存在，文章ID: %s, 元数据键: %s", postId, metaKey);
            Postmeta meta = getPostmeta(postId, metaKey);
            return meta != null;
        }, postId, metaKey);
    }

    @Override
    public List<Record> getPostArchives(String type, String status, int limit) {
        return executeWithResultLogging("getPostArchives", () -> {
            log.debug("获取文章归档，类型: %s, 状态: %s, 限制: %s", type, status, limit);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT YEAR(post_date) as year, MONTH(post_date) as month, COUNT(*) as count ");
            sql.append("FROM wp_posts WHERE 1=1");

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status != ?");
                params.add(Posts.POST_STATUS_TRASH);
            }

            sql.append(" GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY year DESC, month DESC");

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return Db.find(sql.toString(), params.toArray());
        }, type, status, limit);
    }

    @Override
    public boolean updateCommentCount(Object postId, int commentCount) {
        return executeWithBooleanLogging("updateCommentCount", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("更新文章评论数量，文章ID: %s, 评论数量: %s", postId, commentCount);

            int result = Db.update("UPDATE wp_posts SET comment_count = ? WHERE ID = ?", commentCount, postId);
            return result > 0;
        }, postId, commentCount);
    }

    @Override
    public boolean incrementCommentCount(Object postId, int increment) {
        return executeWithBooleanLogging("incrementCommentCount", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("增加文章评论数量，文章ID: %s, 增量: %s", postId, increment);

            int result = Db.update("UPDATE wp_posts SET comment_count = comment_count + ? WHERE ID = ?", increment, postId);
            return result > 0;
        }, postId, increment);
    }

    @Override
    public boolean updateViewCount(Object postId, int viewCount) {
        return executeWithBooleanLogging("updateViewCount", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("更新文章浏览次数，文章ID: %s, 浏览次数: %s", postId, viewCount);

            // 假设浏览次数存储在postmeta中
            return addOrUpdatePostmeta(postId, "views", String.valueOf(viewCount));
        }, postId, viewCount);
    }

    @Override
    public boolean incrementViewCount(Object postId, int increment) {
        return executeWithBooleanLogging("incrementViewCount", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("增加文章浏览次数，文章ID: %s, 增量: %s", postId, increment);

            // 获取当前浏览次数
            String currentViews = getPostmetaValue(postId, "views", "0");
            int newViews = Integer.parseInt(currentViews) + increment;
            return addOrUpdatePostmeta(postId, "views", String.valueOf(newViews));
        }, postId, increment);
    }

    @Override
    public boolean setSticky(Object postId, boolean sticky) {
        return executeWithBooleanLogging("setSticky", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("设置文章置顶状态，文章ID: %s, 置顶: %s", postId, sticky);

            List<Integer> stickyPostIds = getStickyPostIds();

            if (sticky) {
                // 添加到置顶列表
                if (!stickyPostIds.contains(Integer.parseInt(postId.toString()))) {
                    stickyPostIds.add(Integer.parseInt(postId.toString()));
                }
            } else {
                // 从置顶列表移除
                stickyPostIds.remove(Integer.valueOf(postId.toString()));
            }

            // 保存到选项表
            return updateStickyPostsOption(stickyPostIds);
        }, postId, sticky);
    }

    @Override
    public Posts getAdjacentPost(Object postId, String adjacentType, String type, String status) {
        return executeWithResultLogging("getAdjacentPost", () -> {
            validateNotNull(postId, "文章ID不能为空");
            validateNotBlank(adjacentType, "相邻类型不能为空");

            log.debug("获取相邻文章，文章ID: %s, 相邻类型: %s, 类型: %s, 状态: %s", postId, adjacentType, type, status);

            Posts currentPost = getPostWithAnyStatus(postId);
            if (currentPost == null) {
                return null;
            }

            String operator = "prev".equalsIgnoreCase(adjacentType) ? "<" : ">";
            String order = "prev".equalsIgnoreCase(adjacentType) ? "DESC" : "ASC";

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT * FROM wp_posts WHERE post_date ").append(operator).append(" ?");
            params.add(currentPost.getPostDate());

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status != ?");
                params.add(Posts.POST_STATUS_TRASH);
            }

            sql.append(" ORDER BY post_date ").append(order).append(" LIMIT 1");

            return getDao().findFirst(sql.toString(), params.toArray());
        }, postId, adjacentType, type, status);
    }

    @Override
    public Map<String, Posts> getAdjacentPosts(Object postId, String type, String status) {
        return executeWithResultLogging("getAdjacentPosts", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取上一篇和下一篇文章，文章ID: %s, 类型: %s, 状态: %s", postId, type, status);

            Map<String, Posts> adjacentPosts = new HashMap<>();
            adjacentPosts.put("prev", getAdjacentPost(postId, "prev", type, status));
            adjacentPosts.put("next", getAdjacentPost(postId, "next", type, status));

            return adjacentPosts;
        }, postId, type, status);
    }

    @Override
    public Object duplicatePost(Object postId, String newTitle, String status) {
        return executeWithResultLogging("duplicatePost", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("复制文章，原文章ID: %s, 新标题: %s, 状态: %s", postId, newTitle, status);

            Posts originalPost = getPostWithAnyStatus(postId);
            if (originalPost == null) {
                return null;
            }

            // 创建新文章
            Posts newPost = new Posts();
            newPost.setPostAuthor(originalPost.getPostAuthor());
            newPost.setPostDate(new java.util.Date());
            newPost.setPostContent(originalPost.getPostContent());
            newPost.setPostTitle(newTitle != null ? newTitle : originalPost.getPostTitle() + " (复制)");
            newPost.setPostExcerpt(originalPost.getPostExcerpt());
            newPost.setPostStatus(status != null ? status : Posts.POST_STATUS_DRAFT);
            newPost.setCommentStatus(originalPost.getCommentStatus());
            newPost.setPingStatus(originalPost.getPingStatus());
            newPost.setPostPassword(originalPost.getPostPassword());
            newPost.setPostName(generateUniqueSlug(newPost.getPostTitle(), null));
            newPost.setToPing(originalPost.getToPing());
            newPost.setPinged(originalPost.getPinged());
            newPost.setPostModified(new java.util.Date());
            newPost.setPostParent(originalPost.getPostParent());
            newPost.setGuid(""); // GUID会在保存时生成
            newPost.setMenuOrder(originalPost.getMenuOrder());
            newPost.setPostType(originalPost.getPostType());
            newPost.setPostMimeType(originalPost.getPostMimeType());
            newPost.setCommentCount(0l);

            if (!newPost.save()) {
                log.error("保存复制文章失败");
                return null;
            }

            // 复制元数据
            List<Postmeta> originalMetas = getPostmetas(postId);
            if (originalMetas != null && !originalMetas.isEmpty()) {
                List<Postmeta> newMetas = new ArrayList<>();
                for (Postmeta originalMeta : originalMetas) {
                    Postmeta newMeta = new Postmeta();
                    newMeta.setPostId(new BigInteger(newPost.getID().toString()));
                    newMeta.setMetaKey(originalMeta.getMetaKey());
                    newMeta.setMetaValue(originalMeta.getMetaValue());
                    newMetas.add(newMeta);
                }
                savePostMetas(newPost.getID(), newMetas);
            }

            return newPost.getID();
        }, postId, newTitle, status);
    }

    @Override
    public boolean batchUpdateStatus(List<Object> postIds, String status) {
        return executeWithBooleanLogging("batchUpdateStatus", () -> {
            validateNotNull(postIds, "文章ID列表不能为空");
            validateNotBlank(status, "文章状态不能为空");

            log.debug("批量更新文章状态，文章数量: %s, 新状态: %s", postIds.size(), status);

            if (postIds.isEmpty()) {
                return true;
            }

            String inClause = buildInClause(postIds);
            List<Object> params = new ArrayList<>();
            params.add(status);
            params.addAll(postIds);

            int result = Db.update("UPDATE wp_posts SET post_status = ? WHERE ID IN (" + inClause + ")", params.toArray());
            return result > 0;
        }, postIds.size(), status);
    }

    @Override
    public boolean batchDeletePosts(List<Object> postIds, boolean permanent) {
        return executeWithBooleanLogging("batchDeletePosts", () -> {
            validateNotNull(postIds, "文章ID列表不能为空");

            log.debug("批量删除文章，文章数量: %s, 永久删除: %s", postIds.size(), permanent);

            if (postIds.isEmpty()) {
                return true;
            }

            if (permanent) {
                // 永久删除
                String inClause = buildInClause(postIds);
                List<Object> params = new ArrayList<>(postIds);

                // 先删除元数据
                Db.update("DELETE FROM wp_postmeta WHERE post_id IN (" + inClause + ")", params.toArray());

                // 再删除文章
                int result = Db.update("DELETE FROM wp_posts WHERE ID IN (" + inClause + ")", params.toArray());
                return result > 0;
            } else {
                // 移动到回收站
                return batchUpdateStatus(postIds, Posts.POST_STATUS_TRASH);
            }
        }, postIds.size(), permanent);
    }

    @Override
    public boolean batchSetCategories(List<Object> postIds, List<Object> categoryIds) {
        return executeWithBooleanLogging("batchSetCategories", () -> {
            validateNotNull(postIds, "文章ID列表不能为空");

            log.debug("批量设置文章分类，文章数量: %s, 分类数量: %s", postIds.size(), categoryIds != null ? categoryIds.size() : 0);

            // 这里需要实现文章和分类的关系设置
            // 假设使用wp_term_relationships表
            // 由于实现较复杂，这里提供基本框架
            try {
                // 删除现有分类关系
                String postInClause = buildInClause(postIds);
                List<Object> deleteParams = new ArrayList<>(postIds);
                Db.update("DELETE FROM wp_term_relationships WHERE object_id IN (" + postInClause + ") AND term_taxonomy_id IN (SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = 'category')", deleteParams.toArray());

                // 添加新的分类关系
                if (categoryIds != null && !categoryIds.isEmpty()) {
                    for (Object postId : postIds) {
                        for (Object categoryId : categoryIds) {
                            Record relationship = new Record();
                            relationship.set("object_id", postId);
                            relationship.set("term_taxonomy_id", categoryId);
                            Db.save("wp_term_relationships", relationship);
                        }
                    }
                }

                return true;
            } catch (Exception e) {
                log.error("批量设置文章分类异常", e);
                return false;
            }
        }, postIds.size(), categoryIds != null ? categoryIds.size() : 0);
    }

    @Override
    public boolean batchSetTags(List<Object> postIds, List<Object> tagIds) {
        return executeWithBooleanLogging("batchSetTags", () -> {
            validateNotNull(postIds, "文章ID列表不能为空");

            log.debug("批量设置文章标签，文章数量: %s, 标签数量: %s", postIds.size(), tagIds != null ? tagIds.size() : 0);

            // 实现逻辑与batchSetCategories类似
            try {
                // 删除现有标签关系
                String postInClause = buildInClause(postIds);
                List<Object> deleteParams = new ArrayList<>(postIds);
                Db.update("DELETE FROM wp_term_relationships WHERE object_id IN (" + postInClause + ") AND term_taxonomy_id IN (SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = 'post_tag')", deleteParams.toArray());

                // 添加新的标签关系
                if (tagIds != null && !tagIds.isEmpty()) {
                    for (Object postId : postIds) {
                        for (Object tagId : tagIds) {
                            Record relationship = new Record();
                            relationship.set("object_id", postId);
                            relationship.set("term_taxonomy_id", tagId);
                            Db.save("wp_term_relationships", relationship);
                        }
                    }
                }

                return true;
            } catch (Exception e) {
                log.error("批量设置文章标签异常", e);
                return false;
            }
        }, postIds.size(), tagIds != null ? tagIds.size() : 0);
    }

    @Override
    public boolean changeAuthor(List<Object> postIds, Object newAuthorId) {
        return executeWithBooleanLogging("changeAuthor", () -> {
            validateNotNull(postIds, "文章ID列表不能为空");
            validateNotNull(newAuthorId, "新作者ID不能为空");

            log.debug("更改文章作者，文章数量: %s, 新作者ID: %s", postIds.size(), newAuthorId);

            if (postIds.isEmpty()) {
                return true;
            }

            String inClause = buildInClause(postIds);
            List<Object> params = new ArrayList<>();
            params.add(newAuthorId);
            params.addAll(postIds);

            int result = Db.update("UPDATE wp_posts SET post_author = ? WHERE ID IN (" + inClause + ")", params.toArray());
            return result > 0;
        }, postIds.size(), newAuthorId);
    }

    @Override
    public List<String> getPostStatuses() {
        return executeWithResultLogging("getPostStatuses", () -> {
            log.debug("获取文章状态列表");
            List<String> statuses = new ArrayList<>();
            statuses.add(Posts.POST_STATUS_PUBLISH);
            statuses.add(Posts.POST_STATUS_DRAFT);
            statuses.add(Posts.POST_STATUS_PENDING);
            statuses.add(Posts.POST_STATUS_PRIVATE);
            statuses.add(Posts.POST_STATUS_TRASH);
            statuses.add(Posts.POST_STATUS_AUTO_DRAFT);
            statuses.add(Posts.POST_STATUS_INHERIT);
            return statuses;
        });
    }

    @Override
    public Map<String, Map<String, Integer>> getPostTypeStatusCounts() {
        return executeWithResultLogging("getPostTypeStatusCounts", () -> {
            log.debug("获取文章类型的状态统计");

            Map<String, Map<String, Integer>> result = new HashMap<>();

            List<Record> records = Db.find("SELECT post_type, post_status, COUNT(*) as count FROM wp_posts GROUP BY post_type, post_status");

            for (Record record : records) {
                String postType = record.getStr("post_type");
                String postStatus = record.getStr("post_status");
                Integer count = record.getInt("count");

                if (!result.containsKey(postType)) {
                    result.put(postType, new HashMap<>());
                }

                result.get(postType).put(postStatus, count);
            }

            return result;
        });
    }

    @Override
    public boolean validatePost(Posts post) {
        return executeWithBooleanLogging("validatePost", () -> {
            validateNotNull(post, "文章对象不能为空");

            log.debug("验证文章数据");

            // 基本验证
            if (StrKit.isBlank(post.getPostTitle())) {
                return false;
            }

            if (StrKit.isBlank(post.getPostContent())) {
                return false;
            }

            if (StrKit.isBlank(post.getPostType())) {
                return false;
            }

            // 状态验证
            List<String> validStatuses = getPostStatuses();
            if (!validStatuses.contains(post.getPostStatus())) {
                return false;
            }

            return true;
        }, post != null ? post.getPostTitle() : "null");
    }

    @Override
    public String generateUniqueSlug(String title, Object postId) {
        return executeWithResultLogging("generateUniqueSlug", () -> {
            validateNotBlank(title, "文章标题不能为空");

            log.debug("生成唯一别名，标题: %s, 文章ID: %s", title, postId);

            // 生成基础slug
            String baseSlug = SlugKit.slugify(title);
            String slug = baseSlug;
            int counter = 1;

            // 检查是否唯一
            while (!isSlugUnique(slug, postId)) {
                slug = baseSlug + "-" + counter;
                counter++;
            }

            return slug;
        }, title, postId);
    }

    @Override
    public boolean isSlugUnique(String slug, Object postId) {
        return executeWithBooleanLogging("isSlugUnique", () -> {
            validateNotBlank(slug, "文章别名不能为空");

            log.debug("检查别名是否唯一，别名: %s, 文章ID: %s", slug, postId);

            List<Object> params = new ArrayList<>();
            params.add(slug);

            StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM wp_posts WHERE post_name = ?");

            if (postId != null) {
                sql.append(" AND ID != ?");
                params.add(postId);
            }

            Long count = Db.queryLong(sql.toString(), params.toArray());
            return count != null && count == 0;
        }, slug, postId);
    }

    @Override
    public List<Posts> getPostRevisions(Object postId) {
        return executeWithResultLogging("getPostRevisions", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取文章修订版本，文章ID: %s", postId);
            return getDao().find("SELECT * FROM wp_posts WHERE post_parent = ? AND post_type = ? ORDER BY post_date DESC",
                    postId, Posts.POST_TYPE_REVISION);
        }, postId);
    }

    @Override
    public boolean restoreRevision(Object postId, Object revisionId) {
        return executeWithBooleanLogging("restoreRevision", () -> {
            validateNotNull(postId, "文章ID不能为空");
            validateNotNull(revisionId, "修订版本ID不能为空");

            log.debug("恢复文章到指定修订版本，文章ID: %s, 修订版本ID: %s", postId, revisionId);

            Posts currentPost = getPostWithAnyStatus(postId);
            Posts revisionPost = getPostWithAnyStatus(revisionId);

            if (currentPost == null || revisionPost == null) {
                return false;
            }

            // 恢复内容
            currentPost.setPostContent(revisionPost.getPostContent());
            currentPost.setPostTitle(revisionPost.getPostTitle());
            currentPost.setPostExcerpt(revisionPost.getPostExcerpt());
            currentPost.setPostModified(new java.util.Date());

            return currentPost.update();
        }, postId, revisionId);
    }

    @Override
    public int cleanOldRevisions(int days) {
        return executeWithResultLogging("cleanOldRevisions", () -> {
            log.debug("清理过期的文章修订版本，保留天数: %s", days);

            String sql = "DELETE FROM wp_posts WHERE post_type = ? AND post_date < DATE_SUB(NOW(), INTERVAL ? DAY)";
            int result = Db.update(sql, Posts.POST_TYPE_REVISION, days);
            log.debug("清理了 %s 个修订版本", result);
            return result;
        }, days).intValue();
    }

    @Override
    public List<Posts> getPostAttachments(Object postId) {
        return executeWithResultLogging("getPostAttachments", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取文章附件，文章ID: %s", postId);
            return getDao().find("SELECT * FROM wp_posts WHERE post_parent = ? AND post_type = ? ORDER BY post_date DESC",
                    postId, Posts.POST_TYPE_ATTACHMENT);
        }, postId);
    }

    @Override
    public Object getFeaturedImage(Object postId) {
        return executeWithResultLogging("getFeaturedImage", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取文章特色图片，文章ID: %s", postId);
            return getPostmetaValue(postId, "_thumbnail_id");
        }, postId);
    }

    @Override
    public boolean setFeaturedImage(Object postId, Object attachmentId) {
        return executeWithBooleanLogging("setFeaturedImage", () -> {
            validateNotNull(postId, "文章ID不能为空");
            validateNotNull(attachmentId, "附件ID不能为空");

            log.debug("设置文章特色图片，文章ID: %s, 附件ID: %s", postId, attachmentId);
            return addOrUpdatePostmeta(postId, "_thumbnail_id", attachmentId.toString());
        }, postId, attachmentId);
    }

    @Override
    public boolean deleteFeaturedImage(Object postId) {
        return executeWithBooleanLogging("deleteFeaturedImage", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("删除文章特色图片，文章ID: %s", postId);
            return deletePostmeta(postId, "_thumbnail_id");
        }, postId);
    }

    @Override
    public boolean isPasswordProtected(Object postId) {
        return executeWithBooleanLogging("isPasswordProtected", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("检查文章是否有密码保护，文章ID: %s", postId);
            Posts post = getPostWithAnyStatus(postId);
            return post != null && StrKit.notBlank(post.getPostPassword());
        }, postId);
    }

    @Override
    public boolean verifyPostPassword(Object postId, String password) {
        return executeWithBooleanLogging("verifyPostPassword", () -> {
            validateNotNull(postId, "文章ID不能为空");
            validateNotNull(password, "密码不能为空");

            log.debug("验证文章密码，文章ID: %s", postId);
            Posts post = getPostWithAnyStatus(postId);
            return post != null && password.equals(post.getPostPassword());
        }, postId);
    }

    @Override
    public String getPostExcerpt(Object postId, int length) {
        return executeWithResultLogging("getPostExcerpt", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取文章摘要，文章ID: %s, 长度: %s", postId, length);

            Posts post = getPostWithAnyStatus(postId);
            if (post == null) {
                return "";
            }

            // 如果有手动设置的摘要，直接返回
            if (StrKit.notBlank(post.getPostExcerpt())) {
                return post.getPostExcerpt();
            }

            // 否则从内容生成摘要
            return generateExcerpt(post.getPostContent(), length);
        }, postId, length);
    }

    @Override
    public String generateExcerpt(String content, int length) {
        return executeWithResultLogging("generateExcerpt", () -> {
            validateNotNull(content, "文章内容不能为空");

            log.debug("生成文章摘要，内容长度: %s, 摘要长度: %s", content.length(), length);

            // 移除HTML标签
            String plainText = content.replaceAll("<[^>]+>", "");

            // 截取指定长度
            if (plainText.length() <= length) {
                return plainText;
            }

            return plainText.substring(0, length) + "...";
        }, content.length(), length);
    }

    @Override
    public int getReadingTime(Object postId) {
        return executeWithResultLogging("getReadingTime", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取文章阅读时间，文章ID: %s", postId);

            Posts post = getPostWithAnyStatus(postId);
            if (post == null) {
                return 0;
            }

            // 估算阅读时间（按平均阅读速度200字/分钟）
            String content = post.getPostContent();
            String plainText = content.replaceAll("<[^>]+>", "");
            int wordCount = plainText.length();

            // 中文按字符数计算，英文按单词数计算会更准确
            int readingTime = (int) Math.ceil(wordCount / 200.0);

            return Math.max(1, readingTime); // 至少1分钟
        }, postId).intValue();
    }

    @Override
    public List<String> getContentImages(Object postId) {
        return executeWithResultLogging("getContentImages", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取文章内容中的图片，文章ID: %s", postId);

            Posts post = getPostWithAnyStatus(postId);
            if (post == null) {
                return new ArrayList<>();
            }

            List<String> images = new ArrayList<>();
            String content = post.getPostContent();

            // 简单的正则表达式匹配img标签
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("<img[^>]+src=\"([^\">]+)\"");
            java.util.regex.Matcher matcher = pattern.matcher(content);

            while (matcher.find()) {
                images.add(matcher.group(1));
            }

            return images;
        }, postId);
    }

    @Override
    public List<Posts> getPostsByMeta(String metaKey, String metaValue, String compare, String type, String status) {
        return executeWithResultLogging("getPostsByMeta", () -> {
            validateNotBlank(metaKey, "元数据键不能为空");

            log.debug("根据自定义字段查询文章，元数据键: %s, 元数据值: %s, 比较符: %s, 类型: %s, 状态: %s",
                    metaKey, metaValue, compare, type, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT p.* FROM wp_posts p ");
            sql.append("INNER JOIN wp_postmeta pm ON p.ID = pm.post_id ");
            sql.append("WHERE pm.meta_key = ?");
            params.add(metaKey);

            if (StrKit.notBlank(metaValue)) {
                sql.append(" AND pm.meta_value ").append(compare).append(" ?");
                params.add(metaValue);
            }

            if (StrKit.notBlank(type)) {
                sql.append(" AND p.post_type = ?");
                params.add(type);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND p.post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND p.post_status != ?");
                params.add(Posts.POST_STATUS_TRASH);
            }

            sql.append(" ORDER BY p.post_date DESC");

            return getDao().find(sql.toString(), params.toArray());
        }, metaKey, metaValue, compare, type, status);
    }

    @Override
    public List<Posts> getChildPages(Object parentId, String status) {
        return executeWithResultLogging("getChildPages", () -> {
            validateNotNull(parentId, "父页面ID不能为空");

            log.debug("获取子页面，父页面ID: %s, 状态: %s", parentId, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT * FROM wp_posts WHERE post_parent = ? AND post_type = ?");
            params.add(parentId);
            params.add(Posts.POST_TYPE_PAGE);

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            }

            sql.append(" ORDER BY menu_order, post_title");

            return getDao().find(sql.toString(), params.toArray());
        }, parentId, status);
    }

    @Override
    public List<Posts> getMenuItems(Object menuId) {
        return executeWithResultLogging("getMenuItems", () -> {
            validateNotNull(menuId, "菜单ID不能为空");

            log.debug("获取菜单项，菜单ID: %s", menuId);

            // 假设菜单项存储在wp_posts中，post_type为nav_menu_item，并通过meta关联菜单
            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT p.* FROM wp_posts p ");
            sql.append("INNER JOIN wp_postmeta pm ON p.ID = pm.post_id ");
            sql.append("WHERE p.post_type = ? AND pm.meta_key = '_menu_item_menu_item_parent' ");
            sql.append("AND pm.meta_value = ? ORDER BY p.menu_order");

            params.add(Posts.POST_TYPE_NAV_MENU_ITEM);
            params.add(menuId);

            return getDao().find(sql.toString(), params.toArray());
        }, menuId);
    }

    @Override
    public void clearPostCache(Object postId) {
        executeWithResultLogging("clearPostCache", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("清理文章缓存，文章ID: %s", postId);
            // 这里可以实现具体的缓存清理逻辑
            // 例如：cache.remove("post_" + postId);
            return null;
        }, postId);
    }

    @Override
    public void batchClearPostCache(List<Object> postIds) {
        executeWithResultLogging("batchClearPostCache", () -> {
            validateNotNull(postIds, "文章ID列表不能为空");

            log.debug("批量清理文章缓存，文章数量: %s", postIds.size());
            for (Object postId : postIds) {
                clearPostCache(postId);
            }
            return null;
        }, postIds.size());
    }

    @Override
    public String exportPosts(List<Object> postIds) {
        return executeWithResultLogging("exportPosts", () -> {
            log.debug("导出文章数据，文章数量: %s", postIds != null ? postIds.size() : 0);

            // 这里可以实现文章数据的导出逻辑
            // 可以导出为JSON、XML等格式
            // 由于实现较复杂，这里返回空字符串
            return "";
        }, postIds != null ? postIds.size() : 0);
    }

    @Override
    public boolean importPosts(String importData, Object authorId) {
        return executeWithBooleanLogging("importPosts", () -> {
            validateNotBlank(importData, "导入数据不能为空");
            validateNotNull(authorId, "作者ID不能为空");

            log.debug("导入文章数据，数据长度: %s, 作者ID: %s", importData.length(), authorId);

            // 这里可以实现文章数据的导入逻辑
            // 可以解析JSON、XML等格式的数据并创建文章
            // 由于实现较复杂，这里返回false
            return false;
        }, importData.length(), authorId);
    }

    /**
     * 根据作者获取文章列表
     * Service层职责：单一的条件查询操作
     *
     * @param authorId 作者ID
     * @return 文章列表
     */
    public List<Posts> getByAuthor(Object authorId) {
        return executeWithResultLogging("getByAuthor", () -> {
            validateNotNull(authorId, "作者ID不能为空");

            log.debug("根据作者获取文章列表，作者ID: %s", authorId);

            String sql = "SELECT * FROM wp_posts WHERE post_type = ? AND post_author = ? ORDER BY post_date DESC";
            return getDao().find(sql, Posts.POST_TYPE_POST, authorId);
        }, authorId);
    }

    @Override
    public List<Posts> getRecentPosts(int limit, String type, String status) {
        return executeWithResultLogging("getRecentPosts", () -> {
            log.debug("获取最新文章，限制: %s, 类型: %s, 状态: %s", limit, type, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT * FROM wp_posts WHERE 1=1");

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            } else {
                sql.append(" AND post_type = ?");
                params.add(Posts.POST_TYPE_POST);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status = ?");
                params.add(Posts.POST_STATUS_PUBLISH);
            }

            sql.append(" ORDER BY post_date DESC");

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return getDao().find(sql.toString(), params.toArray());
        }, limit, type, status);
    }

    @Override
    public List<Posts> getRelatedPosts(Object postId, int limit) {
        return executeWithResultLogging("getRelatedPosts", () -> {
            validateNotNull(postId, "文章ID不能为空");

            log.debug("获取相关文章，文章ID: %s, 限制: %s", postId, limit);

            // 简单的相关文章实现：基于相同分类和标签
            // 实际项目中可以使用更复杂的算法

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder();

            sql.append("SELECT DISTINCT p.* FROM wp_posts p ");
            sql.append("INNER JOIN wp_term_relationships tr1 ON p.ID = tr1.object_id ");
            sql.append("INNER JOIN wp_term_taxonomy tt1 ON tr1.term_taxonomy_id = tt1.term_taxonomy_id ");
            sql.append("INNER JOIN wp_term_relationships tr2 ON tt1.term_taxonomy_id = tr2.term_taxonomy_id ");
            sql.append("WHERE tr2.object_id = ? AND p.ID != ? AND p.post_status = ? AND p.post_type = ? ");
            sql.append("ORDER BY p.post_date DESC");

            params.add(postId);
            params.add(postId);
            params.add(Posts.POST_STATUS_PUBLISH);
            params.add(Posts.POST_TYPE_POST);

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return getDao().find(sql.toString(), params.toArray());
        }, postId, limit);
    }

    @Override
    public List<Posts> getPostsByCategory(Object categoryId, int limit, String status) {
        return executeWithResultLogging("getPostsByCategory", () -> {
            validateNotNull(categoryId, "分类ID不能为空");

            log.debug("根据分类获取文章，分类ID: %s, 限制: %s, 状态: %s", categoryId, limit, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder();

            sql.append("SELECT p.* FROM wp_posts p ");
            sql.append("INNER JOIN wp_term_relationships tr ON p.ID = tr.object_id ");
            sql.append("INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id ");
            sql.append("WHERE tt.term_taxonomy_id = ? AND p.post_type = ?");
            params.add(categoryId);
            params.add(Posts.POST_TYPE_POST);

            if (StrKit.notBlank(status)) {
                sql.append(" AND p.post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND p.post_status = ?");
                params.add(Posts.POST_STATUS_PUBLISH);
            }

            sql.append(" ORDER BY p.post_date DESC");

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return getDao().find(sql.toString(), params.toArray());
        }, categoryId, limit, status);
    }

    @Override
    public List<Posts> getPostsByTag(Object tagId, int limit, String status) {
        return executeWithResultLogging("getPostsByTag", () -> {
            validateNotNull(tagId, "标签ID不能为空");

            log.debug("根据标签获取文章，标签ID: %s, 限制: %s, 状态: %s", tagId, limit, status);

            // 实现与getPostsByCategory类似，只是taxonomy不同
            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder();

            sql.append("SELECT p.* FROM wp_posts p ");
            sql.append("INNER JOIN wp_term_relationships tr ON p.ID = tr.object_id ");
            sql.append("INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id ");
            sql.append("WHERE tt.term_taxonomy_id = ? AND tt.taxonomy = 'post_tag' AND p.post_type = ?");
            params.add(tagId);
            params.add(Posts.POST_TYPE_POST);

            if (StrKit.notBlank(status)) {
                sql.append(" AND p.post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND p.post_status = ?");
                params.add(Posts.POST_STATUS_PUBLISH);
            }

            sql.append(" ORDER BY p.post_date DESC");

            if (limit > 0) {
                sql.append(" LIMIT ?");
                params.add(limit);
            }

            return getDao().find(sql.toString(), params.toArray());
        }, tagId, limit, status);
    }

    @Override
    public List<Posts> getPostsByAuthor(Object authorId, String type, String status) {
        return executeWithResultLogging("getPostsByAuthor", () -> {
            validateNotNull(authorId, "作者ID不能为空");

            log.debug("根据作者获取文章，作者ID: %s, 类型: %s, 状态: %s", authorId, type, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT * FROM wp_posts WHERE post_author = ?");
            params.add(authorId);

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            } else {
                sql.append(" AND post_type = ?");
                params.add(Posts.POST_TYPE_POST);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status = ?");
                params.add(Posts.POST_STATUS_PUBLISH);
            }

            sql.append(" ORDER BY post_date DESC");

            return getDao().find(sql.toString(), params.toArray());
        }, authorId, type, status);
    }

    @Override
    public List<Posts> getPostsByDate(String year, String month, String type, String status) {
        return executeWithResultLogging("getPostsByDate", () -> {
            validateNotBlank(year, "年份不能为空");

            log.debug("根据日期获取文章，年份: %s, 月份: %s, 类型: %s, 状态: %s", year, month, type, status);

            List<Object> params = new ArrayList<>();
            StringBuilder sql = new StringBuilder("SELECT * FROM wp_posts WHERE 1=1");

            if (StrKit.notBlank(year)) {
                sql.append(" AND YEAR(post_date) = ?");
                params.add(year);
            }

            if (StrKit.notBlank(month)) {
                sql.append(" AND MONTH(post_date) = ?");
                params.add(month);
            }

            if (StrKit.notBlank(type)) {
                sql.append(" AND post_type = ?");
                params.add(type);
            } else {
                sql.append(" AND post_type = ?");
                params.add(Posts.POST_TYPE_POST);
            }

            if (StrKit.notBlank(status)) {
                sql.append(" AND post_status = ?");
                params.add(status);
            } else {
                sql.append(" AND post_status = ?");
                params.add(Posts.POST_STATUS_PUBLISH);
            }

            sql.append(" ORDER BY post_date DESC");

            return getDao().find(sql.toString(), params.toArray());
        }, year, month, type, status);
    }

    @Override
    public Page<Posts> paginate(int pageNumber, int pageSize, String type, String status, String keyword,
                                String category, String tag, String month, Boolean sticky, Integer author,
                                String orderBy, String order) {
        return executeWithResultLogging("paginate", () -> {
            log.debug("分页查询文章，页码: %s, 页大小: %s, 类型: %s, 状态: %s, 关键词: %s, 分类: %s, 标签: %s, 月份: %s, 置顶: %s, 作者: %s, 排序: %s %s",
                    pageNumber, pageSize, type, status, keyword, category, tag, month, sticky, author, orderBy, order);

            StringBuilder selectSql = new StringBuilder("FROM wp_posts p WHERE 1=1");
            List<Object> params = new ArrayList<>();

            // 文章类型
            if (type != null) {
                selectSql.append(" AND p.post_type = ?");
                params.add(type);
            } else {
                selectSql.append(" AND p.post_type = 'post'");
            }

            // 文章状态
            if (status != null) {
                selectSql.append(" AND p.post_status = ?");
                params.add(status);
            } else {
                selectSql.append(" AND p.post_status != 'trash' AND p.post_status != 'auto-draft'");
            }

            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                selectSql.append(" AND (p.post_title LIKE ? OR p.post_content LIKE ?)");
                String likeKeyword = "%" + keyword + "%";
                params.add(likeKeyword);
                params.add(likeKeyword);
            }

            // 作者筛选
            if (author != null) {
                selectSql.append(" AND p.post_author = ?");
                params.add(author);
            }

            // 月份筛选
            if (month != null && month.length() == 6) {
                String year = month.substring(0, 4);
                String monthNum = month.substring(4, 6);
                selectSql.append(" AND YEAR(p.post_date) = ? AND MONTH(p.post_date) = ?");
                params.add(year);
                params.add(monthNum);
            }

            // 分类筛选
            if (category != null && !category.trim().isEmpty()) {
                selectSql.append(" AND EXISTS (SELECT 1 FROM wp_term_relationships tr ");
                selectSql.append(" JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id ");
                selectSql.append(" WHERE tr.object_id = p.ID AND tt.taxonomy = 'category' ");

                if (StringKit.isNumeric(category)) {
                    selectSql.append(" AND tt.term_taxonomy_id = ?)");
                    params.add(Integer.parseInt(category));
                } else {
                    selectSql.append(" AND tt.term_id IN (SELECT term_id FROM wp_terms WHERE slug = ?))");
                    params.add(category);
                }
            }

            // 标签筛选
            if (tag != null && !tag.trim().isEmpty()) {
                selectSql.append(" AND EXISTS (SELECT 1 FROM wp_term_relationships tr ");
                selectSql.append(" JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id ");
                selectSql.append(" WHERE tr.object_id = p.ID AND tt.taxonomy = 'post_tag' ");

                if (StringKit.isNumeric(tag)) {
                    selectSql.append(" AND tt.term_taxonomy_id = ?)");
                    params.add(Integer.parseInt(tag));
                } else {
                    selectSql.append(" AND tt.term_id IN (SELECT term_id FROM wp_terms WHERE slug = ?))");
                    params.add(tag);
                }
            }

            // 置顶筛选
            if (sticky != null) {
                List<Integer> stickyPostIds = getStickyPostIds();
                if (!stickyPostIds.isEmpty()) {
                    if (sticky) {
                        selectSql.append(" AND p.ID IN (");
                    } else {
                        selectSql.append(" AND p.ID NOT IN (");
                    }
                    for (int i = 0; i < stickyPostIds.size(); i++) {
                        if (i > 0) selectSql.append(",");
                        selectSql.append("?");
                        params.add(stickyPostIds.get(i));
                    }
                    selectSql.append(")");
                } else if (sticky) {
                    // 如果没有置顶文章且要求置顶，返回空分页
                    return new Page<>(new ArrayList<>(), pageNumber, pageSize, 0, 0);
                }
            }

            // 排序
            String orderByClause = " ORDER BY ";
            if (orderBy != null) {
                orderByClause += orderBy;
            } else {
                orderByClause += "p.post_date";
            }

            if (order != null && ("ASC".equalsIgnoreCase(order) || "DESC".equalsIgnoreCase(order))) {
                orderByClause += " " + order;
            } else {
                orderByClause += " DESC";
            }

            selectSql.append(orderByClause);

            return getDao().paginate(pageNumber, pageSize, "SELECT p.*", selectSql.toString(), params.toArray());
        }, pageNumber, pageSize, type, status, keyword, category, tag, month, sticky, author, orderBy, order);
    }

    /**
     * 统计置顶文章数量
     */
    @Override
    public long countStickyPosts() {
        return executeWithResultLogging("countStickyPosts", () -> {
            // 获取置顶文章ID列表
            List<Integer> stickyPostIds = getStickyPostIds();
            if (stickyPostIds.isEmpty()) {
                return 0L;
            }

            // 构建IN查询
            StringBuilder inClause = new StringBuilder();
            for (int i = 0; i < stickyPostIds.size(); i++) {
                if (i > 0) inClause.append(",");
                inClause.append("?");
            }

            String sql = "SELECT COUNT(*) FROM wp_posts WHERE ID IN (" + inClause + ") AND post_status = ? AND post_type = ?";

            // 构建参数列表
            List<Object> params = new ArrayList<>(stickyPostIds);
            params.add(Posts.POST_STATUS_PUBLISH);
            params.add(Posts.POST_TYPE_POST);

            return Db.queryLong(sql, params.toArray());
        }).longValue();
    }

    /**
     * 按条件统计文章数量
     */
    @Override
    public long countByCondition(String type, String status, String keyword,
                                 String category, String tag, String month, Boolean sticky) {
        return executeWithResultLogging("countByCondition", () -> {
            StringBuilder sqlBuilder = new StringBuilder("SELECT COUNT(*) FROM wp_posts p WHERE 1=1");
            List<Object> params = new ArrayList<>();

            // 文章类型
            if (type != null) {
                sqlBuilder.append(" AND p.post_type = ?");
                params.add(type);
            } else {
                sqlBuilder.append(" AND p.post_type = 'post'");
            }

            // 文章状态
            if (status != null) {
                sqlBuilder.append(" AND p.post_status = ?");
                params.add(status);
            } else {
                sqlBuilder.append(" AND p.post_status != 'trash' AND p.post_status != 'auto-draft'");
            }

            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                sqlBuilder.append(" AND (p.post_title LIKE ? OR p.post_content LIKE ?)");
                String likeKeyword = "%" + keyword + "%";
                params.add(likeKeyword);
                params.add(likeKeyword);
            }

            // 月份筛选
            if (month != null && month.length() == 6) {
                String year = month.substring(0, 4);
                String monthNum = month.substring(4, 6);
                sqlBuilder.append(" AND YEAR(p.post_date) = ? AND MONTH(p.post_date) = ?");
                params.add(year);
                params.add(monthNum);
            }

            // 分类筛选
            if (category != null && !category.trim().isEmpty()) {
                sqlBuilder.append(" AND EXISTS (SELECT 1 FROM wp_term_relationships tr ");
                sqlBuilder.append(" JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id ");
                sqlBuilder.append(" WHERE tr.object_id = p.ID AND tt.taxonomy = 'category' ");

                if (StringKit.isNumeric(category)) {
                    sqlBuilder.append(" AND tt.term_taxonomy_id = ?)");
                    params.add(Integer.parseInt(category));
                } else {
                    sqlBuilder.append(" AND tt.term_id IN (SELECT term_id FROM wp_terms WHERE slug = ?))");
                    params.add(category);
                }
            }

            // 标签筛选
            if (tag != null && !tag.trim().isEmpty()) {
                sqlBuilder.append(" AND EXISTS (SELECT 1 FROM wp_term_relationships tr ");
                sqlBuilder.append(" JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id ");
                sqlBuilder.append(" WHERE tr.object_id = p.ID AND tt.taxonomy = 'post_tag' ");

                if (StringKit.isNumeric(tag)) {
                    sqlBuilder.append(" AND tt.term_taxonomy_id = ?)");
                    params.add(Integer.parseInt(tag));
                } else {
                    sqlBuilder.append(" AND tt.term_id IN (SELECT term_id FROM wp_terms WHERE slug = ?))");
                    params.add(tag);
                }
            }

            // 置顶筛选
            if (sticky != null) {
                List<Integer> stickyPostIds = getStickyPostIds();
                if (!stickyPostIds.isEmpty()) {
                    if (sticky) {
                        sqlBuilder.append(" AND p.ID IN (");
                    } else {
                        sqlBuilder.append(" AND p.ID NOT IN (");
                    }
                    for (int i = 0; i < stickyPostIds.size(); i++) {
                        if (i > 0) sqlBuilder.append(",");
                        sqlBuilder.append("?");
                        params.add(stickyPostIds.get(i));
                    }
                    sqlBuilder.append(")");
                } else if (sticky) {
                    // 如果没有置顶文章且要求置顶，返回0
                    return 0L;
                }
            }

            return Db.queryLong(sqlBuilder.toString(), params.toArray());
        }, type, status, keyword, category, tag, month, sticky).longValue();
    }

    // ============ 私有方法 ============

    /**
     * 获取置顶文章ID列表
     */
    private List<Integer> getStickyPostIds() {
        return executeWithResultLogging("getStickyPostIds", () -> {
            // 从选项表中获取置顶文章ID
            String sql = "SELECT option_value FROM wp_options WHERE option_name = 'sticky_posts'";
            List<Record> records = Db.find(sql);

            if (records != null && !records.isEmpty()) {
                String stickyPostsValue = records.get(0).getStr("option_value");
                if (stickyPostsValue != null && !stickyPostsValue.trim().isEmpty()) {
                    // 解析序列化的PHP数组或逗号分隔的ID列表
                    return parseStickyPostIds(stickyPostsValue);
                }
            }
            return new ArrayList<Integer>();
        });
    }

    /**
     * 更新置顶文章选项
     */
    private boolean updateStickyPostsOption(List<Integer> stickyPostIds) {
        return executeWithBooleanLogging("updateStickyPostsOption", () -> {
            // 序列化ID列表（简单的逗号分隔）
            String value = String.join(",", stickyPostIds.stream().map(String::valueOf).toArray(String[]::new));

            // 检查是否已存在
            String checkSql = "SELECT COUNT(*) FROM wp_options WHERE option_name = 'sticky_posts'";
            Long count = Db.queryLong(checkSql);

            if (count != null && count > 0) {
                // 更新
                int result = Db.update("UPDATE wp_options SET option_value = ? WHERE option_name = 'sticky_posts'", value);
                return result > 0;
            } else {
                // 插入
                Record option = new Record();
                option.set("option_name", "sticky_posts");
                option.set("option_value", value);
                option.set("autoload", "yes");
                return Db.save("wp_options", option);
            }
        }, stickyPostIds.size());
    }

    /**
     * 解析置顶文章ID
     */
    private List<Integer> parseStickyPostIds(String value) {
        return executeWithResultLogging("parseStickyPostIds", () -> {
            List<Integer> ids = new ArrayList<>();
            // 尝试解析序列化的PHP数组
            if (value.startsWith("a:") && value.contains("i:")) {
                // 简单解析PHP序列化数组
                String[] parts = value.split("i:");
                for (String part : parts) {
                    if (part.length() > 0 && Character.isDigit(part.charAt(0))) {
                        int endIndex = part.indexOf(";");
                        if (endIndex > 0) {
                            String idStr = part.substring(0, endIndex);
                            if (StringKit.isNumeric(idStr)) {
                                ids.add(Integer.parseInt(idStr));
                            }
                        }
                    }
                }
            } else {
                // 尝试逗号分隔
                String[] idArray = value.split(",");
                for (String idStr : idArray) {
                    if (StringKit.isNumeric(idStr.trim())) {
                        ids.add(Integer.parseInt(idStr.trim()));
                    }
                }
            }
            return ids;
        }, value);
    }

    /**
     * 构建IN查询子句
     * Service层私有方法：构建SQL IN查询的条件字符串
     *
     * @param items 参数列表
     * @return IN查询子句
     */
    private String buildInClause(List<?> items) {
        if (items == null || items.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < items.size(); i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append("?");
        }
        return sb.toString();
    }
}